package com.boot.dog.web.excetionhandler;

import cn.hutool.core.util.StrUtil;
import com.boot.dog.common.exception.DogException;
import com.boot.dog.common.util.ApiResult;
import com.boot.dog.common.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: MaxLv
 * @Date: 2019/12/2
 */
@Slf4j
@RestControllerAdvice
public class DogExceptionHandler {
    /**
     * 全局异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResult<Void> exception(Exception e) {
        log.error("全局异常信息 ex={}", e.getMessage(), e);
        return Result.fail("系統错误");
    }

    /**
     * 自定义异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(DogException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResult<Void> dogException(DogException e) {
        log.warn("自定义异常信息 ex={}", e.getMessage(), e);
        return Result.warn(e.getMessage());
    }

    /**
     * validation
     *
     * @param e
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResult<Void> validException(MethodArgumentNotValidException e) {
        List<String> messages = e.getBindingResult().getFieldErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.toList());
        log.warn("参数验证异常信息 ex={}", StrUtil.join(",", messages));
        return Result.warn(StrUtil.join(",<br/>", messages));
    }
}
